import http, { Server, ServerResponse } from 'http';
import querystring, { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring';  //查询字符串相关
import MySQLService from './MySQLService';
import { Config } from '../Config';
import Logger from '../utils/Logger';
import fs from 'fs';
import path from 'path';

class HttpService {

    // 创建一个web服务器
    server: Server = http.createServer((req, res) => {
        res.setHeader("content-type", "text/html; charset=utf-8");
        res.setHeader("Access-Control-Allow-Origin", "*")
        res.setHeader("Access-Control-Allow-Headers", "*")

        let postBody = "";
        req.on('data', function (data) {
            postBody += data;
        });
        req.on('end', ()=> {
            switch (req.url) {
                case "/checkVersion":
                    this.checkVersion(JSON.parse(postBody), res);
                    break;
                case "/login":
                    this.login(JSON.parse(postBody), res);
                    break;
                case "/getRankingList":
                    this.getRankingList(res);
                    break;
                case "/downloadManual":
                    this.returnJsonFile(res);
                    break;
                default:
                    Logger.error("未知的" + req.url);
                    break;
            }
        })
    });

    start() {
        this.server.listen(8080, () => {
            Logger.log("HTTP服务启动成功~");
        });
    }

    /** 比对服务器版本号 */
    checkVersion(obj:any, res: ServerResponse) {
        let version_client = obj.version
        Logger.log("客户端版本号：" + version_client + "， 服务器版本号：" + Config.VERSION);
        let result
        if (version_client != Config.VERSION) {
            result = { "code": 400, "message": "请更新游戏版本" }
        } else {
            result = { "code": 0, "message": "版本比对成功" }
        }
        res.end(JSON.stringify(result));
    }

    /** 登录|注册 */
    login(obj:any, res: ServerResponse) {
        MySQLService.selectByUsername(obj.username, (sql_resluts) => {
            let result: Object;
            let user:any;
            user = sql_resluts[0];
            if (typeof(user) != undefined && user != null) {
                //登录
                if (user.password == obj.password) {
                    if (user.is_logining == 0) {
                        Logger.log("用户登录：" + obj.username);
                        result = { "code": 0, "message": "登录成功", "data": user };
                    } else {
                        result = { "code": 400, "message": "该账号已登录", "data": null }
                    }
                } else {
                    result = { "code": 400, "message": "密码错误", "data": null }
                }
            } else {
                // //注册
                // MySQLService.insertUser(obj.username, obj.password);
                // result = { "code": 1, "message": "注册成功", "data": null }
                result = { "code": 400, "message": "用户不存在", "data": null }
            }
            res.end(JSON.stringify(result));
        });
    }


    /** 获取排行榜 */
    getRankingList(res: ServerResponse) {
        MySQLService.selectRankingList(data=>{
            let result = { "code": 0, "message": "排行榜获取成功", "data": data }
            res.end(JSON.stringify(result));
        });
    }


    /** 返回棋谱json文件 */
    returnJsonFile(res: ServerResponse) {
       // 假设请求的文件路径
        let filePath = path.join(__dirname, '..', '..', '棋谱', 'manual.json');
        // 检查文件是否存在
        fs.stat(filePath, (err, stats) => {
            if (err) {
                res.statusCode = 404;
                res.end('File not found');
                return;
            }
            // 设置响应头
            res.setHeader('Content-Type', 'application/json');
            res.setHeader('Content-Length', stats.size);
            res.setHeader('Content-Disposition', 'attachment; filename=example.json');

            // 读取文件并返回
            const readStream = fs.createReadStream(filePath);
            readStream.pipe(res);
            readStream.on('error', (readErr) => {
                res.statusCode = 500;
                res.end('Error reading file');
            });
        }); 
    }
}

export default new HttpService();